package com.hare.system_server.auth;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hare.auth.base.BaseLoginUser;
import com.hare.common.exception.ServiceException;
import com.hare.common.global.constant.BaseConstant;
import com.hare.common.global.constant.SqlConstant;
import com.hare.common.global.enums.ResultCode;
import com.hare.system_api.po.SysAdmin;
import com.hare.system_server.mapper.SysUserMapper;
import com.hare.system_server.serice.SysMenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @program: Hare
 * @description: 用户认证处理
 * @author: Hare
 * @create: 2022-06-19 15:42
 * @Version 6.0.1
 **/
@Service
public class AuthUserDetails implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(AuthUserDetails.class);

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysMenuService sysMenuService;


    /**
     * 根据用户名查找用户,判断用户是否能登录
     *
     * @param userName
     * @return 封装了用户信息及权限相关信息
     * @throws
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws ServiceException {
        QueryWrapper<SysAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SqlConstant.USER_NAME, userName);
        queryWrapper.last(SqlConstant.LIMIT_ONE);
        // 根据用户名查询用户
        SysAdmin sysAdmin = sysUserMapper.selectOne(queryWrapper);
        // 权限集合
        Set<String> preSet = null;
        if (ObjectUtil.isNotNull(sysAdmin)) {
            preSet = sysMenuService.selectPreGetByUserId(sysAdmin.getId());
        }
        if (ObjectUtil.isNull(sysAdmin)) {
            log.info("***********用户 {} 不存在*****************", userName);
            throw new ServiceException(ResultCode.USER_NOT_FOUNT.getCode(), String.format(ResultCode.USER_NOT_FOUNT.getMessage(),userName));
        } else if (sysAdmin.getStatus() == BaseConstant.NUMBER_ONE) {
            log.info("***********用户 {} 已停用*****************", userName);
            throw new ServiceException(ResultCode.USER_STOP_USING.getCode(), String.format(ResultCode.USER_STOP_USING.getMessage(),userName));
        }
        return loginUser(sysAdmin, preSet);
    }


    /**
     * 封装用户信息
     *
     * @param sysAdmin 用户信息
     * @param set      权限
     * @return
     */
    private BaseLoginUser loginUser(SysAdmin sysAdmin, Set<String> set) {
        return new BaseLoginUser(sysAdmin.getId(), sysAdmin.getUserName(), sysAdmin.getPassword(), set);
    }
}
